package com.system.core.sms;

import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Component;

import com.system.core.sms.dto.mail.MailConfigProperty;
import com.system.core.sms.dto.mail.MailSendReq;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;
import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
public class MailComponent {

	private final Session mailSession;
	private final MailConfigProperty mailConfigProperty;

	/**
	 * host: smtp.qq.com
	 * port: 587
	 * auth: true
	 * tls: true
	 * @param mailSendReq
	 * @throws UnsupportedEncodingException
	 */
	public void send(MailSendReq mailSendReq) throws UnsupportedEncodingException {
		try {
			// 创建邮件消息对象
			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(mailConfigProperty.getUserName())); // 发件人邮箱
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(String.join(",", mailSendReq.getReceiverAddresses()))); // 收件人邮箱
			message.setSubject(MimeUtility.encodeText(mailSendReq.getSubject(), "UTF-8", "B")); // 邮件主题
			message.setText(mailSendReq.getContent()); // 邮件内容
			// 发送邮件
			Transport.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
